<?php
class ProductCategoryController extends BaseController {
    protected $layout = 'layouts.admin';
	public function index()
	{
		$categories = ProductCategory::paginate(Config::get('app.page_row'));
		$this->layout->content = View::make('admin.product_category.index')->with(compact('categories') );
	}
	
	public function add()
	{
		if ( Input::server('REQUEST_METHOD') == 'POST'){
			$data = Input::get('data');
			$Category = new ProductCategory();
			if ( empty($data['alias'])){
				$data['alias'] = $data['title'];
			}
			foreach ($data as $k=>$v) {
				$Category->$k = $v;
			}
			$specs_ids = Input::get('specs');
			$Category->specs = is_array($specs_ids) ? join(',', $specs_ids) : '';
			if ( $Category->save() ) {
				return Redirect::to(route('admin.product_category.index'))->withMessage('successfull');				
			}else{
				
			}
		}else {
			$categories = ProductCategory::all();
			$specs = Specificant::all();
			$this->layout->content = View::make('admin.product_category.add')->with(compact('categories', 'specs') );
		}		
	}
	
	public function edit($id)
	{
		$cat = ProductCategory::find($id);
		if ( Input::server('REQUEST_METHOD') == 'POST'){
			$data = Input::get('data');
			foreach ($data as $k=>$v) {
				$cat->$k = $v;
			}
			$specs_ids = Input::get('specs');
			$cat->specs = is_array($specs_ids) ? join(',', $specs_ids) : '';
			if ( $cat->save() ) {
				return Redirect::to(route('admin.product_category.index'))
					->with('success', '<strong>注册成功。</strong>');

			}
		}else{
			$categories = ProductCategory::where('id','<>',$id)->get();
			$specs = Specificant::all();
			$this->layout->content = View::make('admin.product_category.edit', compact('cat','categories' ,'specs') );
		}
	}
	
	public function drop($id)
	{
		$cat = ProductCategory::find($id);
		if ($cat) {
			$products = Product::where('category_id',$id)->get();
			foreach ($products as $product) {
				ProductSpec::where('product_id', $product->id)->delete();
				ProductAttribute::where('product_id', $product->id)->delete();
				$product->delete();
			}
			$cat->delete();
			return Redirect::route('admin.product_category.index')->with('success', '删除成功。');

		}else{
			return Redirect::route('admin.product_category.index')->with('error', '没有找到。');
		}
	}
}